import express from 'express';
import { body, validationResult } from 'express-validator';
import { Order, UserQuota } from '../models/index.js';
import { catchAsync, BusinessError, NotFoundError } from '../middleware/errorHandler.js';
import { success } from '../utils/response.js';

const router = express.Router();

// 支付回调处理（微信支付）
router.post('/payment/wechat/callback',
  [
    body('order_no').notEmpty().withMessage('订单号不能为空'),
    body('payment_method').equals('wechat').withMessage('支付方式必须是wechat'),
    body('external_order_no').notEmpty().withMessage('外部订单号不能为空'),
    body('transaction_id').optional().notEmpty().withMessage('微信交易号不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { order_no, payment_method, external_order_no, transaction_id } = req.body;
    
    const order = await Order.findByOrderNo(order_no);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    if (order.status !== 'pending') {
      throw new BusinessError('订单状态异常');
    }
    
    if (order.isExpired()) {
      throw new BusinessError('订单已过期');
    }
    
    // 标记订单为已支付
    await order.markAsPaid({
      payment_method,
      external_order_no,
      transaction_id
    });
    
    // 创建用户额度
    await UserQuota.createQuota({
      user_id: order.user_id,
      quota_type: order.quota_type,
      target_id: order.target_id,
      total_count: order.purchase_count,
      used_count: 0,
      remaining_count: order.purchase_count,
      expires_at: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000) // 1年后过期
    });
    
    res.json(success({
      order_no: order.order_no,
      status: 'paid'
    }, '支付成功'));
  })
);

// 支付回调处理（支付宝）
router.post('/payment/alipay/callback',
  [
    body('order_no').notEmpty().withMessage('订单号不能为空'),
    body('payment_method').equals('alipay').withMessage('支付方式必须是alipay'),
    body('external_order_no').notEmpty().withMessage('外部订单号不能为空'),
    body('trade_no').optional().notEmpty().withMessage('支付宝交易号不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { order_no, payment_method, external_order_no, trade_no } = req.body;
    
    const order = await Order.findByOrderNo(order_no);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    if (order.status !== 'pending') {
      throw new BusinessError('订单状态异常');
    }
    
    if (order.isExpired()) {
      throw new BusinessError('订单已过期');
    }
    
    // 标记订单为已支付
    await order.markAsPaid({
      payment_method,
      external_order_no,
      trade_no
    });
    
    // 创建用户额度
    await UserQuota.createQuota({
      user_id: order.user_id,
      quota_type: order.quota_type,
      target_id: order.target_id,
      total_count: order.purchase_count,
      used_count: 0,
      remaining_count: order.purchase_count,
      expires_at: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000) // 1年后过期
    });
    
    res.json(success({
      order_no: order.order_no,
      status: 'paid'
    }, '支付成功'));
  })
);

// 通用支付回调处理（用于测试和模拟）
router.post('/payment/callback',
  [
    body('order_no').notEmpty().withMessage('订单号不能为空'),
    body('payment_method').isIn(['wechat', 'alipay']).withMessage('支付方式无效'),
    body('external_order_no').notEmpty().withMessage('外部订单号不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { order_no, payment_method, external_order_no } = req.body;
    
    const order = await Order.findByOrderNo(order_no);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    if (order.status !== 'pending') {
      throw new BusinessError('订单状态异常');
    }
    
    if (order.isExpired()) {
      throw new BusinessError('订单已过期');
    }
    
    // 标记订单为已支付
    await order.markAsPaid({
      payment_method,
      external_order_no
    });
    
    // 创建用户额度
    await UserQuota.createQuota({
      user_id: order.user_id,
      quota_type: order.quota_type,
      target_id: order.target_id,
      total_count: order.purchase_count,
      used_count: 0,
      remaining_count: order.purchase_count,
      expires_at: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000) // 1年后过期
    });
    
    res.json(success({
      order_no: order.order_no,
      status: 'paid'
    }, '支付成功'));
  })
);

export default router;
